from django.shortcuts import render
from users.forms import ProfileForm,UserForm
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.contrib.auth.decorators	import	login_required
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.contrib import messages
from users.models import UserProfile
# from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.decorators	import	login_required
from django.contrib.auth import authenticate, login,logout
import gvcode,random
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
# Create your views here.

def userlogin(request):
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        verificationcode = request.POST['verificationcode']
        if not verificationcode.lower() == request.session.get('check_code').lower():
            value = "验证码错误，请重新输入"
            return  render(request,'login.html',{'res_u':value})
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return HttpResponseRedirect('/')
        else:
            value = '用户或密码错误：' + username
            print(111)
            return render(request, 'login.html', {'res_u': value})
    else:
        return render(request, 'login.html')

def verificationcode(request):
    f = BytesIO()
    img, code = gvcode.generate(fg_color=(random.randint(10,300),random.randint(50,150),random.randint(50,150)))
    request.session['check_code'] = code
    img.save(f,'PNG')
    return HttpResponse(f.getvalue())

def userlogout(request):
    logout(request)
    return render(request, 'login.html')

@login_required
def userlist(request):
    uservalue = User.objects.all()
    return  render(request,'users/list.html',{'users':uservalue})



def useradd(request):
    if request.POST:
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            # request.POST['password'] = make_password(request.POST['password'])
            user_form.save()
            return HttpResponseRedirect('/users/list/')
        else:
           # messages.error(request, messages.INFO,('Please correct the error below.'))
            return HttpResponse('错误')
    else:
        return HttpResponseRedirect('/users/list/')

def userchange(request,pk):
    u = User.objects.get(pk=pk)
    if request.POST:
        try:
            uform = UserForm(request.POST,instance=u)
            proform = ProfileForm(request.POST,instance=u.userprofile)
            if uform.is_valid() and proform.is_valid():
                uform.save()
                proform.save()
                return HttpResponseRedirect('/users/list/')
        except Exception as e:
            return HttpResponse(e)
    else:
        return render(request,'users/change.html',{'user':u})


def userdel(request,pk):
    try:
        u = User.objects.get(pk=pk)
        u.delete()
    except Exception as e:
        print(e)
    else:
        return HttpResponseRedirect('/users/list/')

def usersearch(request):
    if request.POST:
        pass
    else:
        return HttpResponseRedirect('/users/list/')
